#ifndef _MOTOR_H
#define _MOTOR_H
#ifdef  __cplusplus
    extern "C" {
#endif
/*-----------------------------------------------------------------------
|                               Includes                                |
-----------------------------------------------------------------------*/
#include "main.h"
#include "tim.h"
#include "bsp_pid.h"
/*-----------------------------------------------------------------------
|                                define                                 |
-----------------------------------------------------------------------*/
//*** <<< Use Configuration Wizard in Context Menu >>> ***
//<h> Direction Setting
//<i> 方向设置
//<q> MotorL DirFlip <i> 左电机运动方向翻转	
#define MotorL_DirFlip 0
//<q> MotorR DirFlip <i> 右电机运动方向翻转
#define MotorR_DirFlip 1
//<q> MotorL DirFlip <i> 左电机编码器方向翻转
#define MotorL_EncFlip 1
//<q> MotorR DirFlip <i> 右电机编码器方向翻转
#define MotorR_EncFlip 0
//</h>

//<h> Motor Setting 
//<i> 电机参数
//<o> Motor Max Speed (rpm) <i> 电机最大转速
#define MotorSpeedMax 300 
//<o> Motor Encoder Count Per Cycle <i> 电机一圈的脉冲数
#define MotorEncoders (28*13*4)
//<o> Diameter Of Wheel (mm) <i> 轮胎直径
#define WheelSize 68
//</h>
//<q> Encoder Enable <i> 使能编码器
#define MotorEncoderEnable 1
//<q> Speed PID Enable <i> 使能PID速度环
#define MotorPIDSpeedEnable 1
//*** <<< end of configuration section >>>    ***

typedef struct Motor_Structure
{
	TIM_HandleTypeDef *phtimxV;//PWM
	uint16_t TIMCH;
	int rate;	  // 设定速率
#if MotorEncoderEnable == 1
	TIM_HandleTypeDef *phtimxE;//Encoder
	float v;		  // 真实速度(转速)
	int v_Enc;	  // 脉冲速度
	int8_t dir;	  // 方向
	long x;		  // 位移
	long encoder; // 编码器总计数值
#endif
#if MotorPIDSpeedEnable == 1
	uint8_t pidEN;
	int speed;    // 设定速度
	pid_t PID;
#endif
} Motor_t;


/*-----------------------------------------------------------------------
|                             API FUNCTION                              |
-----------------------------------------------------------------------*/
/* @brief 刹车 */
#define MotorL_Brake()     do{MDirL1_GPIO_Port->BSRR |= MDirL1_Pin;  MDirL2_GPIO_Port->BSRR |= MDirL2_Pin;}while(0)
#define MotorR_Brake()     do{MDirR1_GPIO_Port->BSRR |= MDirR1_Pin;  MDirR2_GPIO_Port->BSRR |= MDirR2_Pin;}while(0)
/* @brief 启动电机PWM */
#define MotorL_Start()    HAL_TIM_PWM_Start(MotorL.phtimxV, MotorL.TIMCH)
#define MotorR_Start()    HAL_TIM_PWM_Start(MotorR.phtimxV, MotorR.TIMCH)

extern Motor_t MotorL;
extern Motor_t MotorR;

void Motor_Init(void);
void MotorL_Set_Rate(int rate);
void MotorL_Stop(void);
void MotorR_Set_Rate(int rate);
void MotorR_Stop(void);
#if MotorEncoderEnable == 1
int MotorL_GetEncoderCnt(void);
int MotorR_GetEncoderCnt(void);
void Motor_Speed_Check(void);
void User_TIM_PECallback(TIM_HandleTypeDef *htim);
#if MotorPIDSpeedEnable == 1
void Motor_PID_Server(void);
#endif
#endif
#ifdef __cplusplus
}
#endif
#endif

